---@class RedRob.BufferMgr
local BufferMgr = RedRob.CreateSingleton("BufferMgr")
local this = BufferMgr

function BufferMgr.OnCreate()
    ---@type table<number,RedRob.Buffer[]>
    this.bufferList = {}
    ---@type RedRob.Buffer[]
    this.removedList = {}
    RedRob.ClientBattle.RegisterUpdateCallback(this.Update)
end
function BufferMgr.OnDestroy()
    if this.bufferList then
        for k,v in pairs(this.bufferList) do
            for id,buff in pairs(v) do
                buff:OnDestroy()
            end
        end
    end
    this.bufferList = nil
end
function BufferMgr.GetBuffList(targetId)
    return this.bufferList[targetId]
end
---@return RedRob.Buffer
function BufferMgr.GetBuff(targetId,buffId)
    local _list = this.bufferList[targetId]
    if not _list then return nil end
    return _list[buffId]
end
function BufferMgr.CreateBuff(buffId,overlay,targetId,during)
    local b = RedRob.PoolMgr.GetBufferFromPool()--RedRob.Buffer.New()
    b:OnCreate()
    b:Set(buffId,overlay,targetId,during)
    this.AddBuff(b)
end
---@param buff RedRob.Buffer
function BufferMgr.ToPool(buff)
    if buff == nil then return end
    buff:OnDestroy()
    local _list = this.bufferList[buff.targetId]
    if _list then
        _list[buff.buffId] = nil
    end
    RedRob.PoolMgr.ReturnBufferToPool(buff)
end
---@param buff RedRob.Buffer
function BufferMgr.AddBuff(buff)
    local list = this.GetBuffList(buff.targetId)
    if not list then
        list = {}
        this.bufferList[buff.targetId] = list
    end
    if list[buff.buffId] ~= nil then
        return
    end
    list[buff.buffId] = buff
end
---buffId 为 nil 删除所有的buff
function BufferMgr.RemoveBuff(targetId,buffId)
    local buffList = this.bufferList[targetId]
    if not buffList then return end
    if buffId == nil then
        table.clear(this.removedList)
        for k,v in pairs(buffList) do
            table.insert(this.removedList,v)
        end
        for k,v in pairs(this.removedList) do
            this.ToPool(v)
        end
    else
        local buff = buffList[buffId]
        if not buff then return end
        this.ToPool(buff)
    end
end
function BufferMgr.Update(dt)
    table.clear(this.removedList)
    local temp = TablePool.Get()
    for k,v in pairs(this.bufferList) do
        temp[k] = v
    end
    for k,v in pairs(temp) do
        for id,buff in pairs(v) do
            buff:Update(dt)
            if buff:IsDie() then
                table.insert(this.removedList,buff)
            end
        end
    end
    TablePool.ReleaseDeeper(temp,false)
    --
    for k,v in pairs(this.removedList) do
        this.ToPool(v)
    end
    table.clear(this.removedList)
end
